#include "WallTurret.h"

#define PI 3.14f
#define GUN_ANGLE PI/6
#define R_HOUSE 30
#define TIME_FIND 500
#include "Box.h"
#include "Sprite.h"
#include "ShareComponents.h"
#include "BulletManager.h"
#include "Camera.h"

WallTurret::WallTurret(Box* _box) : Object(_box,Obj_STATIC)
{

}


WallTurret::~WallTurret(void)
{
}

void WallTurret::init()
{
	_sAngle = RSManager::getInstance()->getSprite(BLOCK_HOUSE_ANGLE);
	_sSimple = RSManager::getInstance()->getSprite(BLOCK_HOUSE_SIMPLE);
	_sStart = RSManager::getInstance()->getSprite(BLOCK_HOUSE_START);		
	_sprite =NULL;
	delay = 0;
	gundelay = 0;
	_hits=8;
	_isAlive=true;
	_obj= Obj_STATIC;
	_sAngle->Reset(7);
	_colBox->_v.x=0;
	_colBox->_v.y =0;

}
void WallTurret::update()
{
	//set state
	if(_hits<0) _isAlive = false;
	bool ck1 = _box->getRight() < gl_camera->getRightSide();
	bool ck2 = _box->getLeft() < gl_camera->getLeftSide() - 10;

	state = !ck1 || ck2 ? SIMPLE : GUN;		
	if(state == SIMPLE)
	{
		_sprite = _sSimple;
	}
	else
	{
		_sprite = _sAngle;		
	}

	// process state
	switch (state)
	{
	case SIMPLE:		
		delay += GAME_TIME;
		if(delay>200)
		{
			delay=0;
			_sprite->Next();
		}
		_colBox->_position.x = 0;
		_colBox->_position.y = 0;
		_colBox-> _size.x=0;
		_colBox->_size.y =0;

		break;
	case START:
		_sprite=_sStart;break;
	case GUN:
		_colBox->_position=_box->_position;
		_colBox->_size= _box->_size;
		D3DXVECTOR2 p = gl_player->getCenterPos() - _box->getCenterPos();
		float _agl = atan2(p.y,p.x);
		int index_sprite = getIndex(_agl);
		gundelay += GAME_TIME;
		if(gundelay > 800)
		{
			gundelay = 0.0f;
			if(index_sprite == _sprite->GetCurrentIndex())
			{
				BulletManager::getInstance()->shoot(B_E,this->_obj,_box->getCenterPos(),(index_sprite) * 3.14f / 8.0f);
			}
		}

		delay += GAME_TIME;
		if(delay > 500)
		{
			delay=0;
			int current_index = _sprite->GetCurrentIndex();
			int nguoc;
			int xuoi;
			if(current_index > index_sprite)
			{
				nguoc = 16 - current_index + index_sprite;
				xuoi = current_index - index_sprite;
				if(nguoc < xuoi)
				{

					_sprite->Reset((current_index  + 1)% 16);	
				}
				else
				{
					_sprite->Reset(current_index -1);				
				}
				
			}
			else if(current_index < index_sprite)
			{
				nguoc = index_sprite - current_index ;
				xuoi = 16 - index_sprite + current_index;
				if(xuoi < nguoc)
				{
					int xdex = current_index - 1 < 0 ? 16 + current_index - 1 : current_index - 1;
					_sprite->Reset(xdex);
				}
				else
				{
					_sprite->Reset(current_index  + 1);
				}
				
			}

		}
		break;
	}		
}

void WallTurret::render()
{	
	_sprite->Render(_box->_position);	
}

Box* WallTurret::getCollisionBox()
{
	return _colBox;
}

int WallTurret::getIndex(float _alg)
{
	if(_alg < 0.0f)
	{
		_alg = 2 * 3.14 + _alg;
	}
	return int(_alg * 8 / 3.14f);
}
